const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');
const auth = require('../middleware/auth');

// 获取用户列表（仅管理员和辅导员可访问）
router.get('/', auth, async (req, res) => {
  try {
    // 检查权限
    if (!['admin', 'counselor'].includes(req.user.role)) {
      return res.status(403).json({ message: '权限不足' });
    }

    let query = 'SELECT id, name, avatar, role, userId, department, classId, phone, email, createTime, lastLoginTime FROM users';
    let params = [];

    // 如果是辅导员，只能查看自己负责的班级的学生
    if (req.user.role === 'counselor') {
      query += ` WHERE role = 'student' AND classId IN (
        SELECT classId FROM counselor_class_relation WHERE counselorId = ?
      )`;
      params.push(req.user.id);
    }

    const [users] = await pool.query(query, params);
    res.json(users);
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});
// 获取用户详细信息
router.get('/profile', auth, async (req, res) => {
  try {
    // 从请求参数或认证信息中获取用户ID
    const userId = req.query.userId || req.user?.id;
    
    // 检查用户ID是否存在
    if (!userId) {
      return res.status(400).json({ message: '缺少用户ID参数' });
    }
    
    console.log('获取用户资料，用户ID:', userId);
    
    const [users] = await pool.execute(
      `SELECT u.*, c.className 
       FROM users u
       LEFT JOIN classes c ON u.classId = c.id
       WHERE u.id = ? OR u.userId = ?`,
      [userId, userId]
    );

    if (!users || users.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 移除敏感信息
    delete users[0].password;
    
    // 添加默认字段，以便前端代码不需要修改
    const userData = {
      ...users[0],
      bio: users[0].bio || '', // 使用已有bio或默认空字符串
      gender: users[0].gender || '' // 使用已有gender或默认空字符串
    };
    
    res.json(userData);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});
// 获取单个用户信息
router.get('/:id', auth, async (req, res) => {
  try {
    const userId = req.params.id;

    // 检查权限（只能查看自己或管理员/辅导员可以查看所有）
    if (req.user.id != userId && !['admin', 'counselor'].includes(req.user.role)) {
      return res.status(403).json({ message: '权限不足' });
    }

    const [rows] = await pool.query(
      'SELECT id, name, avatar, role, userId, department, classId, phone, email, createTime, lastLoginTime FROM users WHERE id = ?',
      [userId]
    );

    if (rows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }

    res.json(rows[0]);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新用户信息
router.put('/:id', auth, async (req, res) => {
  try {
    const userId = req.params.id;
    const { name, phone, email, avatar } = req.body;

    // 检查权限（只能更新自己或管理员可以更新所有）
    if (req.user.id != userId && req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }

    await pool.query(
      'UPDATE users SET name = ?, phone = ?, email = ?, avatar = ? WHERE id = ?',
      [name, phone, email, avatar, userId]
    );

    // 记录更新日志
    await pool.query(
      'INSERT INTO logs (userId, userName, userRole, action, target, targetId, content, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [req.user.id, req.user.name, req.user.role, 'update', 'users', userId, '更新用户信息', req.ip]
    );

    res.json({ message: '用户信息更新成功' });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除用户（仅管理员可操作）
router.delete('/:id', auth, async (req, res) => {
  try {
    const userId = req.params.id;

    // 检查权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }

    // 获取用户信息（用于日志记录）
    const [userRows] = await pool.query('SELECT name FROM users WHERE id = ?', [userId]);
    if (userRows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }

    await pool.query('DELETE FROM users WHERE id = ?', [userId]);

    // 记录删除日志
    await pool.query(
      'INSERT INTO logs (userId, userName, userRole, action, target, targetId, content, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [req.user.id, req.user.name, req.user.role, 'delete', 'users', userId, `删除用户: ${userRows[0].name}`, req.ip]
    );

    res.json({ message: '用户删除成功' });
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});


module.exports = router;